<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('运营费用认领单-新增')" />
	<th:block th:include="include :: businessCSS" />
    <style>
        .main-content{position: relative;}
        .topbtns{position:fixed;top: 0;width: 100%;z-index: 9999;background-color: #fff;}
        .preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
        .preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
        /* .layui-border-box{height: 350px !important;}
        .layui-table-body{height: 240px !important;} */
        .layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}

    </style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
        <div class="topbtns"><th:block th:include="include :: business_btn" /></div>
	    <div class="north" style="background-color: #fff;margin-top: 55px;">
			<div class="forminput"></div>
    	</div>
        <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
        <div>
            <table class="layui-hide" id="dhtable" lay-filter="dhtable"></table>
            <script type="text/html" id="zjtoolbar">
                <div style="padding: 16px;display: flex;justify-content: space-between;">
                    <div  style="font-weight: 700;font-size: 18px;">运营费用认领单详情</div>
            		<div>
                        <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="addbtn" id="btn-sh">新增</button>
                        <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button>
            		</div>
            	</div>
            </script>
        </div>
        <th:block th:include="include :: pageFooter" /> 
    </form>
	</div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: inlineJS" />
<script th:src="@{/dhecp/js/dh-toFixed.js}"></script>


<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "business/productbasis",
    	prefix2 = ctx + "base/company";

	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];
	var moduleTable = [[${moduleTable}]];
	var enableEdit = [[${enableEdit}]];
    //商品表格基础信息
	var gridColumns = [[${gridColumns}]];
	var gridColumnsZJ = [[${gridColumnsZJ}]];

    //表格基础信息
    var List=[[${List}]];
    //子件列表数据
    var sonList=[[${sonList}]];

    var listData1= [];
   

	var $,layer,form,table,nid,noTable;

    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
        beforeInit();//表单初始化之前的动作集合
		//初始化操作
		headcom3()
        nid=$('#nid').val()
         // 保存按钮事件变化
        $(function(){
           $('.tp-save').attr('onclick','')
           $('.tp-save').attr('lay-filter','btn-edit')
           $('.tp-save').attr('lay-submit',true)
        })


        // 保存操作
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                         layer.msg(v.fieldName+'不能为空')
                         is_return=true
                    }
                }
            })
            if (listData1.length == 0) {
                layer.msg('详情信息不能为空')
                return ;
            }
            var errorMsg = '';
            for(var i=0;i<listData1.length;i++){
                if(listData1[i].paymentTime==undefined || listData1[i].paymentTime==null || listData1[i].paymentTime==''){
                    errorMsg = '详情信息中，收款时间信息为空！';
                }
                if(listData1[i].paymentAmount==undefined || listData1[i].paymentAmount==null || listData1[i].paymentAmount==''){
                    errorMsg = '详情信息中，付款金额为空！';
                }
                if(listData1[i].paymentBankName==undefined || listData1[i].paymentBankName==null || listData1[i].paymentBankName==''){
                    errorMsg = '详情信息中，付款银行户名信息为空！';
                }
                if(listData1[i].registerBankName==undefined || listData1[i].registerBankName==null || listData1[i].registerBankName==''){
                    errorMsg = '详情信息中，登记银行户名信息为空！';
                }
                if(listData1[i].registerAmount==undefined || listData1[i].registerAmount==null || listData1[i].registerAmount==''){
                    errorMsg = '详情信息中，登记金额为空！';
                }

                if(listData1[i].paymentAmount!=undefined && listData1[i].paymentAmount!=null){
                    if(!validateNum(listData1[i].paymentAmount)){
                        errorMsg = '详情信息中，付款金额应为小数！';
                    }
                }
            }
            if (errorMsg != '') {
                layer.msg(errorMsg)
                return ;
            }
            if(is_return) return;
            var money = 0;
            listData1.map((v,i)=>{
                v.iid=i+1
                money = money + Number(v.sjAmount);
            })
            $.modal.loading("正在处理中，请稍后...");
            $.post("/finance/tcwCapitalBusinessCost/editpost",{infoMap:JSON.stringify(data.field),infoItems:JSON.stringify(listData1),sonData:JSON.stringify(listData1)},function(res){
                $.modal.closeLoading();
			 	layer.msg(res.msg);
                if(res.code == 0){
                   window.location.href = '/finance/tcwCapitalBusinessCost/edit?nid=' + res.data;
                }
	        });
        });


		var colsList = gridColumnsZJ.gridBody;
		console.log("colsList",colsList);
        if(enableEdit==1){
            for(var i=0;i<colsList.length;i++){
                if(colsList[i].field=="paymentTime"){
                    colsList[i] = {align:"center",field:"paymentTime",title: "<font class=\"f_red\">*</font>"+"付款时间",width: 200,sort: "true",templet:
                            function(d){
                                return '<span >'+(d.paymentTime!=undefined?d.paymentTime:'')+'</span> ' +
                                    '<i class="layui-icon layui-icon-date" id="paymentTimeSet'+d.LAY_TABLE_INDEX+'" onclick="chooseDataTime(\''+d.LAY_TABLE_INDEX+'\')" style="position:absolute;right:8px;z-index:3; cursor: pointer;"></i>';
                                //return '<input class="layui-input laydate-type-datetime" id="paymentTimeSet'+d.LAY_TABLE_INDEX+'" placeholder="选择付款时间" value='+(d.paymentTime!=undefined?d.paymentTime:null)+' readonly="true">';
                            }
                    }
                }
                if(colsList[i].field=="paymentBankName"){
                    colsList[i] = {align:"center",field:"paymentBankName",title: "<font class=\"f_red\">*</font>"+"付款银行户名",width: 200,sort: "true",templet:
                            function(d){
                                return '<span>'+(d.paymentBankName!=undefined?d.paymentBankName:'')+'</span> ' +
                                    '<i class="layui-icon layui-icon-more" onclick="selectModelByOperatorBankInfo(\''+d.dzBid+'\')" style="position:absolute;right:8px;z-index:3"></i>';

                            }
                    }
                }
                if(colsList[i].field=="registerBankName"){
                    colsList[i] = {align:"center",field:"registerBankName",title: "<font class=\"f_red\">*</font>"+"登记银行户名",width: 200,sort: "true",templet:
                            function(d){
                                return '<span>'+(d.registerBankName!=undefined?d.registerBankName:'')+'</span> ' +
                                    '<i class="layui-icon layui-icon-more" onclick="selectModelByTcwCapitalRegisterClaim(\''+d.dzBid+'\')" style="position:absolute;right:8px;z-index:3"></i>';

                            }
                    }
                }

                if(colsList[i].field=="vDFilesDefault"){
                    colsList[i] = {align:"center",field:"vDFilesDefault",title: "附件",width: 200,sort: "true",templet:
                            function(d){
                                return '<span>'+(d.vDFilesDefault!=undefined?d.vDFilesDefault:'')+'</span> ' +
                                    '<i class="layui-icon layui-icon-upload getDetailUpload" tGuid="'+d.guid+'" tname="vDFilesDefault" style="float:right"></i>';
                                //'<i class="layui-icon layui-icon-upload getDetailUpload" tguid="undefined" tname="vDFilesDefault" style="float:right"></i>';

                            }
                    }
                }


            }

        }

        
        listData1=List ?List:[];

		if(listData1!=null && listData1.length>0){
            for(var i=0;i<listData1.length;i++){
                listData1[i].dzBid = listData1[i].id;
                listData1[i].paymentTime = listData1[i].paymentTime.substring(0, 10);// + " "+listData1[i].paymentTime.substring(11, 19);
                listData1[i].registerTime = listData1[i].registerTime.substring(0, 10);// + " "+listData1[i].registerTime.substring(11, 19);
            }
        }
        console.log('listData1',listData1);
        var dzBid = 0;
        // 初始化表格
            $.tablelist.init({
                elem: '#dhtable'
                ,data: listData1
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumnsZJ.totalRow
                , cols: [colsList]
                , toolbar: '#zjtoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '320'
                , done: function (res, curr, count) {
                    var options = this;
                    listData1 = table.cache.dhtable;//每次重载都赋值更新表缓存
                    console.log('listData1',listData1);
                    // laydate
                    laydate.render({
                        elem: '.laydate-type-datetime',
                        type: 'datetime',
                        //type: 'date',
                        done: function(value, date, endDate){
                            console.log('value',value); // 日期字符，如： 2017-08-18
                            console.log(date); // 包含年月日时分秒各项值的对象
                            var data = table.getRowData(options.id, this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                            listData1[data.LAY_TABLE_INDEX].paymentTime = value+"";
                            console.log(listData1);
                            table.reload('dhtable', {data:listData1});
                            $('#paymentTimeSet'+data.LAY_TABLE_INDEX).val(value);
                        }
                    });
                    // 获取当前行数据
                    table.getRowData = function(tableId, elem){
                        var index = $(elem).closest('tr').data('index');
                        return table.cache[tableId][index] || {};
                    };
                    detailUpload();
                },success:function(a,b,c){
                        // console.log(a,b,c,9999)
                }
            });

        //详情表格操作
        table.on('toolbar(dhtable)', function (obj) {

            var selectedObject=""
            sessionStorage.setItem('mjdata',JSON.stringify(table.cache.dhtable))
            table.cache.dhtable.map((v,i)=>{
                if(selectedObject){
                    selectedObject+=','+v.dzBid
                }else{
                    selectedObject+=v.dzBid
                }
            })
            switch (obj.event) {
                //新增按钮
                case 'addbtn':
                    var newRes = [];
                    newRes.push({
                        //paymentTime:getDataStr(),
                        dzBid :'new'+dzBid,
                        vDFilesDefault :''
                    })
                    if(listData1){
                        listData1.push(newRes[0]);
                        layui.table.reload('dhtable', {data:listData1});
                    }else{
                        layui.table.reload('dhtable', {data:newRes});
                    }
                    dzBid ++;

                   break;

                   //删除按钮
                case 'mjbtn_save':
                    var objdata=table.checkStatus('dhtable')
                    objdata=objdata.data;
                    console.log('objdata',objdata);
                    listData1= table.cache.dhtable;
                    console.log('listData1',listData1);
                    if(objdata.length>0){
                        objdata.forEach(item => {
                            listData1 = listData1.filter(items => items.dzBid!= item.dzBid);
                        });
                        table.reload('dhtable', {data:listData1});
                    }else{
                        layer.msg("请选择数据");
                    }
                    break;
            };
        });
    });
    function chooseDataTime(index) {
        layui.laydate.render({
            elem: '#paymentTimeSet'+index,
            type: 'date',
            //value:(listData1[index].paymentTime!=undefined&&listData1[index].paymentTime!=null?listData1[index].paymentTime:''),
            done: function(value, date, endDate){
                listData1[index].paymentTime = value+"";
                layui.table.reload('dhtable', {data:listData1});
            }
        });
    }

    function validateNum(val){//验证小数，保留2位小数点

        var patten = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
        return patten.test(val);

    }

    function getDataStr() {
        var today = new Date();

        // 获取年、月、日、时、分、秒
        var year = today.getFullYear();
        var month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
        var day = today.getDate();
        // 格式化输出
        var formattedTime = year + "-" +
            (month < 10 ? "0" : "") + month + "-" +
            (day < 10 ? "0" : "") + day + " 00:00:00";

        return formattedTime;
    }

    //获取资金登记认领表弹框
    function selectModelByTcwCapitalRegisterClaim(dzBid) {
        var paymentBankName = null;
        var paymentBank = null;
        var paymentBankAccount = null;
        var paymentTime = null;
        var paymentAmount = null;
        if(listData1){
            for (let i = 0; i < listData1.length; i++) {
                if(dzBid==listData1[i].dzBid){
                    if(listData1[i].paymentBankName != undefined && listData1[i].paymentBankName != null && listData1[i].paymentBankName != ''){
                        paymentBankName = listData1[i].paymentBankName;
                    }
                    if(listData1[i].paymentBank != undefined && listData1[i].paymentBank != null && listData1[i].paymentBank != ''){
                        paymentBank = listData1[i].paymentBank;
                    }
                    if(listData1[i].paymentBankAccount != undefined && listData1[i].paymentBankAccount != null && listData1[i].paymentBankAccount != ''){
                        paymentBankAccount = listData1[i].paymentBankAccount;
                    }
                    if(listData1[i].paymentTime != undefined && listData1[i].paymentTime != null && listData1[i].paymentTime != ''){
                        paymentTime = listData1[i].paymentTime;
                    }
                    if(listData1[i].paymentAmount != undefined && listData1[i].paymentAmount != null && listData1[i].paymentAmount != ''){
                        paymentAmount = listData1[i].paymentAmount;
                    }
                }
            }
        }
        if(paymentBankName == null){
            layer.msg('请先选择付款银行户名！');
            return ;
        }
        if(paymentBank == null){
            layer.msg('付款开户行为空！');
            return ;
        }
        if(paymentBankAccount == null){
            layer.msg('付款银行账号为空！');
            return ;
        }
        if(paymentTime == null){
            layer.msg('请先填写付款时间！');
            return ;
        }
        if(paymentAmount == null){
            layer.msg('请先填写付款金额！');
            return ;
        }

        layui.layer.open({
            type: 2,
            area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
            fix: false,//不固定
            offset: '10%',//距离顶部
            maxmin: true,//最大最小化
            shade: 0.3,//遮罩
            title: '运营服务商信息',
            content: "/finance/tcwCapitalRegisterClaim/select2?pagetype=radio&by=direct&fmoduleTable="+"TCW_CAPITALREGISTERCLAIM"
                +"&bid="+$('#bid').val()+"&paymentBankName="+paymentBankName+"&paymentBank="+paymentBank+"&paymentBankAccount="+paymentBankAccount
                +"&paymentTime="+paymentTime+" 00:00:00&paymentAmount="+paymentAmount,
            btn: ['确定', '取消'],
            shadeClose: true,// 弹层外区域关闭
            yes: function(index, layero){
                var res = window["layui-layer-iframe" + index].callbackdata();
                console.log('res',res);
                if(res!=null){
                    layui.layer.closeAll();
                    //var mjdata=sessionStorage.getItem('mjdata');
                    if(listData1){
                        //mjdata=JSON.parse(mjdata);
                        var hasChoosed = false;
                        for (let i = 0; i < listData1.length; i++) {
                            if(res.id==listData1[i].capitalRegisterClaimId){
                                hasChoosed = true;
                            }
                        }
                        if(hasChoosed){
                            layui.layer.msg("不可重复选择！");
                            return;
                        }

                        for (let i = 0; i < listData1.length; i++) {
                            if(dzBid==listData1[i].dzBid){
                                listData1[i].registerTime = res.paymentTime;
                                listData1[i].registerBankName = res.paymentBankName;
                                listData1[i].registerBank = res.paymentBank;
                                listData1[i].registerBankAccount = res.paymentBankAccount;
                                listData1[i].registerAmount = res.paymentAmount;
                                listData1[i].capitalRegisterClaimId = res.id;
                            }
                        }
                        layui.table.reload('dhtable', {data:listData1});
                    }else{
                        res.dzBid = dzBid;
                        var newRes = [];
                        newRes.push(res);
                        layui.table.reload('dhtable', {data:newRes});
                    }
                }else{
                    layui.layer.msg("请选择数据");
                }
            }
        });
    }


    //获取运营服务商信息弹框
    function selectModelByOperatorBankInfo(dzBid) {
        var claimCompanyCode = $('#claimCompanyCode').val();
        console.log('claimCompanyCode',claimCompanyCode);
        if(claimCompanyCode==undefined || claimCompanyCode==null || claimCompanyCode==''){
            layui.layer.msg("请先选择运营公司");
            return;
        }

        layui.layer.open({
            type: 2,
            area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
            fix: false,//不固定
            offset: '10%',//距离顶部
            maxmin: true,//最大最小化
            shade: 0.3,//遮罩
            title: '运营服务商信息',
            content: "/finance/tcwCapitalRegister/select2?pagetype=radio&by=direct&fmoduleTable="+"TCW_CAPITALREGISTER"+"&bid="+$('#bid').val()+"&vGsBm="+claimCompanyCode,
            btn: ['确定', '取消'],
            shadeClose: true,// 弹层外区域关闭
            yes: function(index, layero){
                var res = window["layui-layer-iframe" + index].callbackdata();
                console.log('res',res);
                if(res!=null){
                    layui.layer.closeAll();
                    //var mjdata=sessionStorage.getItem('mjdata');
                    if(listData1){
                        for (let i = 0; i < listData1.length; i++) {
                            if(dzBid==listData1[i].dzBid){
                                listData1[i].paymentBankName = res.partnerName;
                                listData1[i].paymentBank = res.vKhh;
                                listData1[i].paymentBankAccount = res.vYhZh;
                            }
                        }
                        console.log('listData1',listData1);
                        layui.table.reload('dhtable', {data:listData1});
                    }else{
                        res.dzBid = dzBid;
                        var newRes = [];
                        newRes.push(res);
                        layui.table.reload('dhtable', {data:newRes});
                    }
                }else{
                    layui.layer.msg("请选择数据");
                }
            }
        });
    }

</script>

</body>
</html>